#include <iostream>
#include <functional>
#include <memory>
#include <thread>
#include <future>
#include <condition_variable>
#include <vector>

class threadpool
{
public:
    using Functor=std::function<void()>;
    threadpool(int thr_count=1):_stop(false)
    {
        for(int i = 0;i<thr_count;++i)
            _threads.emplace_back(&threadpool::entry,this);
    }

    ~threadpool()
    {
        stop();
    }

    template<typename F,typename ...Args>
    auto push(F&& func,Args&& ...args) ->std::future<decltype(func(args...))>
    {
        //1.对传入的函数封装成应该packaged_task任务
        using return_type = decltype(func(args...));
        //完美转发
        auto tmp_func=std::bind(std::forward<F>(func),std::forward<Args>(args)...);
        auto task =std::make_shared<std::packaged_task<return_type()>>(tmp_func);
        std::future<return_type> fu=task->get_future();
        //2.构造一个lambda匿名函数，执行匿名对象
        {
            std::unique_lock<std::mutex> lock(_mutex);
            //3.将匿名函数对象，丢到任务池
            _taskpool.push_back(    [task](){ (*task)(); }    );
            _cv.notify_one();
        }
        return fu;
    }

    void stop()
    {
        if(_stop==true) return;
        _stop=true;
        _cv.notify_all();
        for (auto& thread:_threads)
        {
            thread.join();
        }  
    }

private:
    //线程入口函数
    void entry()
    {
        while(!_stop)
            {
            std::vector<Functor> tem_taskpool;
            {
                //加锁
                std::unique_lock<std::mutex> lock(_mutex);
                //等待任务池不为空 or _stop被置位返回，
                _cv.wait(lock, [this](){return _stop || !_taskpool.empty();} );
                //取出任务执行
                tem_taskpool.swap(_taskpool);
            }

            for(auto& task: tem_taskpool)
            {
                task();
            }
        }
    }

private:
    std::atomic<bool> _stop;//结束标志
    std::vector<Functor> _taskpool;//任务池
    std::mutex _mutex;
    std::condition_variable _cv;
    std::vector<std::thread> _threads;//线程池
};

int add(int a,int b)
{
    return a+b;
}

int main()
{
    threadpool pool;
    for(int i=0;i<10;++i)
    {
        std::future<int> fu = pool.push(add,11,i);
        std::cout<<fu.get()<<std::endl;
    }

    pool.stop();
    return 0;
}